import React, { Component } from 'react';
import { toast, promptBox, cacheTools } from 'nc-lightapp-front';
import { hrAjax as ajax } from 'src/hrpub/common/utils/utils';
import ReferSearch from 'src/hrpub/common/components/referSearch/org';
import HRBack from 'src/hrpub/common/components/hr-back/index';
import { chectFormAction } from 'src/hrcm/public/functions/checkFormAction';
import './index.less';
class Header extends Component {
	constructor(props) {
		super(props);
		this.state = {
			json: this.props.json,
			hrorgobj: null
		};
		this.backToList = this.backToList.bind(this);
		this.handleButtonClick = this.handleButtonClick.bind(this);
		this.handlePageInfoChange = this.handlePageInfoChange.bind(this);
		this.getButtons = this.getButtons.bind(this);
	}
	/* 卡片视图转换为table视图 */
	backToList() {
		const { showMode, updateState, json, toEditFrom, cardPagination, cardViewId } = this.props;
		let allpks = cacheTools.get('allpks');
		if (showMode === 'card-edit') {
			promptBox({
				color: 'warning',
				title: json['cm6011-000030'] /* 国际化处理： 提示*/,
				content: json['cm6011-000001'] /* 国际化处理： 是否确认要取消? */,
				beSureBtnClick: () => {
					updateState(
						{
							showMode: toEditFrom || 'card-browse'
						},
						function() {
							if (toEditFrom === 'list-browse') {
								this.refs.maintable.getTableData();
							} else {
								cardPagination.setCardPaginationId({ id: cardViewId || allpks[0], status: 1 });
							}
						}
					);
				}
			});
		} else {
			updateState({ showMode: 'list-browse' }, function() {
				this.refs.maintable.getTableData();
			});
		}
	}
	/* 重置state */
	resetState() {
		this.setState({
			showAddModal: false,
			showAgreement: false,
			justFrom: null,
			stepData: null,
			setShowBack: false
		});
	}
	/* 事件转移 */
	handleButtonClick(props, event) {
		this[event](props, event);
	}
	/* 新增 */
	add(props, event) {
		this.props.updateState(
			{
				showAddModal: true
			},
			function() {
				this.openAddModal();
			}
		);
	}
	/* 查询 */
	query() {
		const { search, meta, pkOrg } = this.props;
		let _allmeta_ = meta.getMeta();
		_allmeta_['listquery'].items.forEach((item) => {
			if (item.attrcode === 'pk_psnjob.pk_dept') {
				item.queryCondition = {
					pk_hrorg: pkOrg
				};
			}else if(item.attrcode === 'pk_conttext'){
				item.queryCondition = {
					pk_org: pkOrg,
					GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
				}
			}
		});
		search.openAdvSearch('listquery', true);
	}
	/* 修改 */
	edit(props, event) {
		const { showMode, updateState, cardViewId, checkDataPermission, areaCode } = this.props;
		checkDataPermission([ cardViewId ], 'edit', 'contract', () => {
			updateState(
				{
					showMode: 'card-edit',
					toEditFrom: 'card-browse'
				},
				() => {
					chectFormAction('', areaCode.card, this.props, [ areaCode.card ]);
				}
			);
		});
	}
	/* 删除 */
	delete() {
		const { editTable, showMode, areaCode, cardViewId, json, checkDataPermission } = this.props;
		const checked = editTable.getCheckedRows(areaCode.table);
		if (showMode === 'list-browse') {
			if (checked.length === 0) {
				toast({ color: 'warning', content: json['cm6011-000155'] }); /* 国际化处理： 请选择记录！*/
			} else {
				checkDataPermission(
					checked.map((item) => item.data.values.pk_psndoc_sub.value),
					'delete',
					'contract',
					() => {
						promptBox({
							color: 'warning',
							title: json['cm6011-000030'] /* 国际化处理： 提示*/,
							content: json['cm6011-000042'] /* 国际化处理： 您确定要删除选择数据吗？*/,
							beSureBtnClick: () => {
								this._delete_(checked.map((item) => item.data.values.pk_psndoc_sub.value), false);
							}
						});
					}
				);
			}
		} else {
			checkDataPermission([ cardViewId ], 'delete', 'contract', () => {
				promptBox({
					color: 'warning',
					title: json['cm6011-000030'] /* 国际化处理： 提示*/,
					content: json['cm6011-000042'] /* 国际化处理： 您确定要删除选择数据吗？*/,
					beSureBtnClick: () => {
						this._delete_([ cardViewId ], true);
					}
				});
			});
		}
	}
	_delete_(_rowData, _isCard) {
		const self = this;
		const { URLS, pkOrg, button } = self.props;
		ajax({
			url: URLS.delete,
			data: {
				pk_org: pkOrg,
				modename: 'hi_psndoc_ctrt',
				isCard: _isCard,
				allpks: _rowData
			},
			success(res) {
				if (_isCard) {
					const nextpg = self.props.cardPagination.getNextCardPaginationId({ id: _rowData[0] });
					self.props.cardPagination.setCardPaginationId({ id: _rowData[0], status: 3 });
					self.handlePageInfoChange(self.props, nextpg, 1);
					self.props.updateState({
						cardViewId: nextpg
					});
					if (!nextpg) {
						button.setButtonDisabled([ 'edit', 'delete', 'effective', 'refresh' ], true);
					}
				} else {
					self.refresh();
				}
			}
		});
	}
	/* 刷新 */
	refresh() {
		this.props.refresh();
	}
	/* 生效 */
	effective() {
		this.props.takeEffect();
	}
	/* 保存 */
	save() {
		this.props.save();
	}

	/* 取消 */
	cancel() {
		this.backToList();
	}
	/**
     * 查询主组织 节点信息
     */
	searchChange(val) {
		this.props.updateState(
			{
				pkOrg: val.refpk,
				hrorgobj: val
			},
			function() {
				this.refs.maintable.getTableData();
			}
		);
	}
	handlePageInfoChange(props, flag, status = 1) {
		const { updateState } = this.props;
		if (flag) {
			updateState({ cardViewId: flag }, () => {
				props.cardPagination.setCardPaginationId({ id: flag, status: status });
			});
		} else {
			updateState({ cardViewId: null });
			return props.form.EmptyAllFormValue(this.props.areaCode.card);
		}
		if (status === 3) {
			return false;
		}
		var tableData = props.editTable.getAllData(this.props.areaCode.table).rows;
		if (!tableData.length) {
			props.form.EmptyAllFormValue(this.props.areaCode.card);
		} else {
			tableData.forEach((item, index) => {
				if (flag && item.values.pk_psndoc_sub.value === flag) {
					props.form.setAllFormValue({ [this.props.areaCode.card]: { rows: [ item ] } });
				}
			});
		}
	}
	getButtons() {
		const { button, cardPagination, showMode, hasList, pkOrg } = this.props;
		let resEl = {
			operation: null,
			cardPg: null
		};
		switch (showMode) {
			case 'list-browse':
				/* 需要判断hrorgobj.refpk */
				if (pkOrg) {
					this.props.button.setButtonDisabled([ 'delete', 'effective' ], !hasList);
					this.props.button.setButtonDisabled([ 'add' ], false);
					this.props.button.setButtonVisible([ 'query' ], true);
					this.props.button.setButtonVisible([ 'edit' ], false);
				} else {
					this.props.button.setButtonDisabled([ 'add', 'delete', 'effective' ], true);
				}
				resEl.operation = button.createButtonApp({
					area: 'list-header',
					onButtonClick: this.handleButtonClick,
					popContainer: document.querySelector('.operations')
				});
				break;
			case 'card-browse':
				this.props.button.setButtonVisible([ 'edit' ], true);
				this.props.button.setButtonVisible([ 'query' ], false);
				resEl.operation = button.createButtonApp({
					area: 'list-header',
					onButtonClick: this.handleButtonClick,
					popContainer: document.querySelector('.operations')
				});
				resEl.cardPg = cardPagination.createCardPagination({
					handlePageInfoChange: this.handlePageInfoChange
				});
				break;
			case 'card-edit':
				resEl.operation = button.createButtonApp({
					area: 'card-header',
					onButtonClick: this.handleButtonClick,
					popContainer: document.querySelector('.operations')
				});
				break;
			default:
				resEl.operation = button.createButtonApp({
					area: 'list-header',
					onButtonClick: this.handleButtonClick,
					popContainer: document.querySelector('.operations')
				});
		}
		return [ resEl.operation, resEl.cardPg ];
	}
	render() {
		const { areaCode, showMode, hrorgobj, pkOrg } = this.props;
		const setBtns = this.getButtons();
		const display = {
			display: showMode !== 'list-browse' ? 'inline-block' : 'none'
		};
		return (
			<header className="header">
				<div className="search-bar">
					<HRBack onClick={this.backToList} title={areaCode} style={display} />
					<ReferSearch
						showorg={showMode === 'list-browse' ? true : false}
						orgVal={hrorgobj}
						getOrgData={this.searchChange.bind(this)}
						queryCondition={() => {
							return {
								controlType: 0
							};
						}}
					/>
				</div>
				<div className="operations" style={{ display: pkOrg ? 'block' : 'none' }}>
					{setBtns}
				</div>
			</header>
		);
	}
}

export default Header;
